﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Functions;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables
{
    [InjectClass]
    public class SearchRecordServer : ISearchRecordServer
    {
        private readonly ServerRepository _serverRepository;

        public SearchRecordServer(DbContext dbContext) {
            _serverRepository = new ServerRepository(dbContext);
        }

        public async Task<ResponseApiDto> AddAsync(RequestSearchRecordAddDto dto,int bid)
        {
            int affectedRows = 0;
            if (await _serverRepository.searchRecordsEFCore.Query(d => d.SrSearchWord == dto.searchWord).AnyAsync())
            {
                SearchRecord sr = await _serverRepository.searchRecordsEFCore.Query(d => d.SrSearchWord == dto.searchWord).SingleAsync();
                sr.SrSearchTime = DateTime.Now;
                affectedRows += await _serverRepository.searchRecordsEFCore.UpdateAsync(sr);
            }
            else
            {
                SearchRecord sr = new SearchRecord()
                {
                    SrBusinessId = bid,
                    SrSearchTime = DateTime.Now,
                    SrSearchWord = dto.searchWord
                };
                affectedRows += await _serverRepository.searchRecordsEFCore.AddAsync(sr);
            }
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> ClearAllAsync(int bid)
        {
            var iq = _serverRepository.searchRecordsEFCore.Query(d=>d.SrBusinessId==bid);
            int affectedRows =await _serverRepository.searchRecordsEFCore.DeleteAsync(iq);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DeleteAsync(RequestSearchRecordDeleteDto dto, int bid)
        {
            var iq = _serverRepository.searchRecordsEFCore.Query(d => d.SrBusinessId == bid&&d.SrId==dto.id);
            int affectedRows = await _serverRepository.searchRecordsEFCore.DeleteAsync(iq);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> GetAllAsync(int bid)
        {
            var iq = _serverRepository.searchRecordsEFCore.Query(d => d.SrBusinessId == bid);
            List<ResponseSearchRecordDto> data =await iq.Select(d => new ResponseSearchRecordDto {id=d.SrId,searchWord=d.SrSearchWord }).ToListAsync();
            return ResponseApiDto.Ok("数据已获取",data);
        }
    }
}
